"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 数据库备机异常情况下（数据文件丢失），数据库进行备升主
Create At   : 2020/07/20
@zou_jialiang0505328114
Description :
    1、启动主备数据库，判断数据库状态；
    2、主库上建立表空间（指定目录）；
    3、修改主库表空间目录权限；
    4、使用相应表空间建表；
    5、还原权限进行备升主；
Expect      :
    1、启动成功，数据库状态正常
    2、执行成功
    3、执行成功
    4、执行失败，给出合理提示
    5、执行成功
History     :
    2020/12/7 n@ningyali 1、优化脚本；2、teardown中增加主备机对表、表空间及表空间路径的删除
"""

import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.CommonSH import *


class Deletaduit(unittest.TestCase):
    primary_sh = CommonSH('PrimaryDbUser')
    standby1_sh = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case149.py start------------')
        self.rootNode = Node()
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.standby1_root_node = Node(node='Standby1Root')
        self.standby1_user_node = Node(node='Standby1DbUser')
        self.standby2_root_node = Node(node='Standby2Root')
        self.Constant = Constant()
        self.path = os.path.join(os.path.dirname(macro.DB_INSTANCE_PATH), "t_reliability_149")
        self.t_name = "t_reliability_149"
        self.tb_name = "tb_reliability_149"

    def test_startdb(self):
        # 主库上建立表空间（指定目录）；
        self.sql = f'''drop tablespace if exists {self.tb_name};create tablespace {self.tb_name} location '{self.path}' ;'''
        msg = self.primary_sh.executDbSql(self.sql)
        self.log.info(msg)
        for err_msg in self.Constant.SQL_WRONG_MSG:
            self.assertNotIn(err_msg, msg)

        # 修改主库表空间目录权限；
        msg = self.primary_user_node.sh('chmod 000 ' + self.path).result()
        self.log.info(msg)
        self.assertEqual(msg, '')

        # 使用相应表空间建表；
        self.sql1 = f'''drop table if exists {self.t_name};CREATE TABLE {self.t_name}(i int) TABLESPACE {self.tb_name};'''
        msg = self.primary_sh.executDbSql(self.sql1)
        self.log.info(msg)
        self.assertIn('Permission denied', msg)

        # 进行备升主；
        msg1 = self.standby1_sh.executeGsctl('switchover', '', '', get_detail=True)
        self.log.info(msg1)
        self.assertIn('switchover completed', msg1)

        msg = self.standby1_sh.exec_refresh_conf()
        self.assertTrue(msg)

        status = self.primary_sh.getDbClusterStatus('status')
        self.assertTrue(status)

        msg = self.primary_user_node.sh('chmod 700 ' + self.path).result()
        self.log.info(msg)
        self.assertEqual(msg, '')

        # 进行主备还原；
        msg1 = self.primary_sh.executeGsctl('switchover', '', '', get_detail=True)
        self.log.info(msg1)
        self.assertIn('switchover completed', msg1)

        msg = self.primary_sh.exec_refresh_conf()
        self.assertTrue(msg)

    def tearDown(self):
        msg = self.primary_user_node.sh('chmod 700 ' + self.path).result()
        self.log.info(msg)

        self.log.info("--------------------drop tablespace--------------------")
        cmd = f'''drop table if exists {self.t_name}; drop tablespace if exists {self.tb_name};'''
        msg = self.primary_sh.executDbSql(cmd)
        self.log.info(cmd)
        self.log.info(msg)

        self.log.info("--------------------delete file-------------------")
        shell_cmd = f"rm -rf {self.path}"
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        msg = self.standby1_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        msg = self.standby2_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.log.info(
            '------------------------------------reliability_dbsys149.py finish------------------------------------')
